﻿using System;
using System.Linq;
using System.Text;
using System.Web.Mvc;
using System.Web.Routing;
using CP_SchoolForChildren_v0._1.Models.DataModel;
using CP_SchoolForChildren_v0._1.Models.RelatedModel;
using PagedList;

namespace CP_SchoolForChildren_v0._1.Controllers.FE
{
    public class ArticleController : Controller


    {
        private SFCEntities db = new SFCEntities();


        // get current user id
        public int currentUserID()
        {
            var user = from u in db.Users
                       where (u.UserName == User.Identity.Name)
                       select u;
            int userid = user.First().UserID;
            return userid;
        }

        //
        // GET: /Article/
        public ActionResult Index(int? page)
        {
            var article = from u in db.Users
                          from a in db.Articles
                          from c in db.Categories
                          where u.UserID == a.UserID
                          where a.CategoryID == c.CategoryID
                          select new ArticleModel
                                     {
                                         CategoryID = c.CategoryID,
                                         Title = a.Title,
                                         UserID = a.UserID,
                                         ArticleContent = a.ArticleContent,
                                         UserName = u.UserName,
                                         CategoryName = c.CategoryName,
                                         CreatedTime = a.CreatedTime,
                                         ArticleID = a.ArticleID,
                                     };
            int pageSize = 10;
            int pageNumber = (page ?? 1);
            return View(article.OrderByDescending(c => c.CreatedTime).ToPagedList(pageNumber, pageSize));
        }

        [Authorize(Roles = "Editor,Admin")]
        public ActionResult Create()
        {
            var article = new Article();
            ViewBag.CategoryID = new SelectList(db.Categories, "CategoryID", "CategoryName", article.CategoryID);
            return View(article);
        }

        [HttpPost]
        public ActionResult Create(Article article)
        {
            try
            {
                if (ModelState.IsValid)
                {
                    if (article.ArticleContent.Length < 150)
                    {
                        ViewBag.Message = "Nội dung phải lớn hơn 150 kí tự";
                        ViewBag.CategoryID = new SelectList(db.Categories, "CategoryID", "CategoryName",
                                                            article.CategoryID);
                        return View(article);
                    }

                    else if (article.ArticleContent != null && article.Title != null)
                    {
                        int userID = currentUserID();
                        article.CreatedTime = DateTime.Now;
                        article.ArticleContent = Server.HtmlEncode(Server.UrlDecode(article.ArticleContent));
                        article.UserID = userID;
                        db.Articles.Add(article);
                        db.SaveChanges();
                        return RedirectToAction("Details", "Article", new {id = article.ArticleID});
                    }
                    else if (article.Title == null || article.ArticleContent == null)
                    {
                        ViewBag.Message = "Bạn phải nhập đầy đủ các trường";
                        ViewBag.CategoryID = new SelectList(db.Categories, "CategoryID", "CategoryName",
                                                            article.CategoryID);
                        return View(article);
                    }
                }
            }
            catch (Exception)
            {
                ViewBag.CategoryID = new SelectList(db.Categories, "CategoryID", "CategoryName", article.CategoryID);
                ViewBag.Message = "Đã có lỗi trong quá trình tạo bài viết. Vui lòng kiểm tra kết nối và thử lại";
                return View();
            }
            ViewBag.CategoryID = new SelectList(db.Categories, "CategoryID", "CategoryName", article.CategoryID);
            return View(article);
        }

        public ActionResult Details(int id)
        {
            Article article = new Article();
            ViewBag.CategoryID = new SelectList(db.Categories, "CategoryID", "CategoryName", article.CategoryID);
            var arti = from u in db.Users
                       from a in db.Articles
                       from c in db.Categories
                       where u.UserID == a.UserID
                       where a.CategoryID == c.CategoryID
                       where a.ArticleID == id
                       select new ArticleModel
                                  {
                                      Title = a.Title,
                                      ArticleContent = a.ArticleContent,
                                      UserName = u.UserName,
                                      UserID = u.UserID,
                                      CategoryName = c.CategoryName,
                                      CreatedTime = a.CreatedTime,
                                      ArticleID = a.ArticleID,
                                      CategoryID = c.CategoryID,
                                  };
            return View(arti.First());
        }

        [Authorize(Roles = "Editor,Admin")]
        public ActionResult Edit(int id)
        {
            var article = (from a in db.Articles
                           where a.ArticleID == id
                           select a).First();
            int userid = currentUserID();

            var user = (from u in db.Users
                       where (u.UserID == userid)
                       select u).First();

            var roleadmin = db.UserRoles.Single(ur => ur.RoleName == "Admin");
            if (userid == article.UserID || user.RoleID == roleadmin.RoleID)
            {
                ViewBag.CategoryID = new SelectList(db.Categories, "CategoryID", "CategoryName", article.CategoryID);
                return View(article);
            }
            else
            {
                return RedirectToAction("Index", "Article");
            }
        }

        [HttpPost]
        public ActionResult Edit(int id, Article article)
        {
            if (ModelState.IsValid)
            {
                try
                {
                    if (article.ArticleContent == null || article.Title == null)
                    {
                        ViewBag.Message = "Bạn phải nhập đầy đủ các trường";
                        ViewBag.CategoryID = new SelectList(db.Categories, "CategoryID", "CategoryName",
                                                            article.CategoryID);
                        return View(article);
                    }
                    else if (article.Title.Length <5 || article.Title.Length > 250 )
                    {
                        ViewBag.Message = "Tiêu đề phải > 5 và < 250 kí tự";
                        ViewBag.CategoryID = new SelectList(db.Categories, "CategoryID", "CategoryName",
                                                            article.CategoryID);
                        return View(article);
                    }
                    else if (article.ArticleContent.Length <250)
                    {
                        ViewBag.Message = "Nội dung phải > 250 kí tự";
                        ViewBag.CategoryID = new SelectList(db.Categories, "CategoryID", "CategoryName",
                                                            article.CategoryID);
                        return View(article);
                    }
                    else
                    {
                        db.Entry(article).State = System.Data.EntityState.Modified;
                        db.SaveChanges();
                        ViewBag.CategoryID = new SelectList(db.Categories, "CategoryID", "CategoryName",
                                                            article.CategoryID);
                        return RedirectToAction("Details", "Article", new {id = article.ArticleID});
                    }


                }

                catch (Exception)
                {
                    ModelState.AddModelError("", "Đã có lỗi khi kết nối tới hệ thống, xin kiểm tra kết nối và thử lại");
                    ViewBag.CategoryID = new SelectList(db.Categories, "CategoryID", "CategoryName", article.CategoryID);
                    return View(article);
                }
            }
            ViewBag.CategoryID = new SelectList(db.Categories, "CategoryID", "CategoryName", article.CategoryID);
            return View(article);
        }

        [Authorize(Roles = "Editor,Admin")]
        public ActionResult Delete(int id)
        {
            try
            {
                var article = (from a in db.Articles
                               where a.ArticleID == id
                               select a).First();
                int userid = currentUserID();

                var user = (from u in db.Users
                            where (u.UserID == userid)
                            select u).First();

                var roleadmin = db.UserRoles.Single(ur => ur.RoleName == "Admin");

                if (userid == article.UserID || user.RoleID == roleadmin.RoleID)
                {
                    db.Articles.Remove(db.Articles.SingleOrDefault(a => a.ArticleID == id));
                    db.SaveChanges();
                    return RedirectToAction("Index", "Article");
                }

                else
                {
                    ViewBag.Message = "Bạn không có quyền thực hiện thao tác này";
                    return RedirectToAction("Index", "Home");
                }
                
                
            }

            catch (Exception)
            {
                return RedirectToAction("Index", "Article");
            }
        }

        public ActionResult ViewArticleByCategory(int id, int? page)
        {
            var article = from u in db.Users
                          from a in db.Articles
                          from c in db.Categories
                          where u.UserID == a.UserID
                          where a.CategoryID == c.CategoryID
                          where a.CategoryID == id
                          select new ArticleModel
                                     {
                                         CategoryID = c.CategoryID,
                                         Title = a.Title,
                                         ArticleContent = a.ArticleContent,
                                         UserName = u.UserName,
                                         UserID =  u.UserID,
                                         CategoryName = c.CategoryName,
                                         CreatedTime = a.CreatedTime,
                                         ArticleID = a.ArticleID,
                                     };
            int pageSize = 10;
            int pageNumber = (page ?? 1);
            return View(article.OrderByDescending(c => c.CreatedTime).ToPagedList(pageNumber, pageSize));
        }

        [Authorize(Roles = "Editor,Admin")]
        public ActionResult ArticleManagement()
        {
            return View();
        }
    }
}